<template>
  <div class="login-wrapper">
    <!-- 粒子动画背景 -->
    <div class="particle-container">
      <div v-for="n in 20" :key="n" class="particle"></div>
    </div>

    <!-- 页面标题区域 -->
    <div v-if="isLogin" class="page-title">
      <h1 class="title-text">欢迎来到旋转大转盘</h1>
      <div class="title-decoration">
        <div class="decoration-line"></div>
        <div class="decoration-circle"></div>
        <div class="decoration-line"></div>
      </div>
    </div>

    <!-- 登录/注册表单容器 -->
    <div class="login-container" :class="{ 'no-title': !isLogin }">
      <el-card class="login-card">
        <!-- 数字时钟 -->
        <div class="digital-clock">
          <div class="time-segment">
            <span class="time-number">{{ hours }}</span>
          </div>
          <span class="colon">:</span>
          <div class="time-segment">
            <span class="time-number">{{ minutes }}</span>
          </div>
          <span class="colon">:</span>
          <div class="time-segment">
            <span class="time-number">{{ seconds }}</span>
          </div>
        </div>

        <!-- 表单部分 -->
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            class="login-form"
            label-position="top"
            @keyup.enter="handleSubmit"
        >
          <el-form-item prop="username">
            <el-input
                v-model="form.username"
                :prefix-icon="User"
                placeholder="请输入用户名"
                @focus="handleFocus"
                @blur="handleBlur"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="form.password"
                :prefix-icon="Lock"
                type="password"
                placeholder="请输入密码"
                @focus="handleFocus"
                @blur="handleBlur"
            />
          </el-form-item>

          <el-form-item v-if="!isLogin" prop="confirmPassword">
            <el-input
                v-model="form.confirmPassword"
                :prefix-icon="Lock"
                type="password"
                placeholder="请确认密码"
                @focus="handleFocus"
                @blur="handleBlur"
            />
          </el-form-item>

          <el-form-item v-if="!isLogin" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="!isLogin" prop="job">
            <el-select v-model="form.job" placeholder="请选择职位">
              <el-option label="班主任" :value="1" />
              <el-option label="讲师" :value="2" />
              <el-option label="学工主管" :value="3" />
              <el-option label="学生" :value="4" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="!isLogin" prop="phone">
            <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                @focus="handleFocus"
                @blur="handleBlur"
            />
          </el-form-item>

          <div class="captcha-container">
            <el-form-item prop="captcha">
              <div class="captcha-wrapper">
                <el-input
                    v-model="form.captcha"
                    class="captcha-input"
                    placeholder="请输入验证码"
                    @focus="handleFocus"
                    @blur="handleBlur"
                />
                <div class="captcha-box" @click="refreshCaptcha">
                  <span v-html="captchaHTML"></span>
                </div>
                <el-button
                    type="primary"
                    :icon="RefreshRight"
                    circle
                    @click="refreshCaptcha"
                />
              </div>
            </el-form-item>
          </div>

          <div class="button-group">
            <el-button
                type="primary"
                class="submit-btn"
                @click="handleSubmit"
                :loading="loading"
            >
              {{ isLogin ? '登录' : '注册' }}
            </el-button>
            <div class="toggle-btn-container">
              <el-button class="toggle-btn" @click="toggleMode">
                {{ isLogin ? '没有账号?去注册' : '已有账号?去登录' }}
                <div class="button-effect"></div>
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { RefreshRight, User, Lock } from '@element-plus/icons-vue'
import { login, register } from '@/api/user'

const router = useRouter()
const store = useStore()
const formRef = ref<FormInstance>()
const isLogin = ref(true)
const loading = ref(false)

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  verifyCode: '',
  gender: 1,
  job: 4,
  phone: ''
})

// 验证规则
const validatePassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'))
  } else if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
    callback(new Error('密码必须包含字母和数字'))
  } else {
    callback()
  }
}

const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateCaptcha = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else if (value.toLowerCase() !== form.verifyCode.toLowerCase()) {
    callback(new Error('验证码输入有误，请重新输入'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, validator: validateCaptcha, trigger: 'blur' }
  ]
});


// 时钟数据
const currentTime = ref(new Date())
const hours = computed(() => currentTime.value.getHours().toString().padStart(2, '0'))
const minutes = computed(() => currentTime.value.getMinutes().toString().padStart(2, '0'))
const seconds = computed(() => currentTime.value.getSeconds().toString().padStart(2, '0'))

let timerInterval: number

onMounted(() => {
  timerInterval = window.setInterval(() => {
    currentTime.value = new Date()
  }, 1000)
  refreshCaptcha()
})

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
})

// 处理表单提交
// handleSubmit 中的代码修改
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证码校验
      if (form.captcha.toLowerCase() !== form.verifyCode.toLowerCase()) {
        ElMessage.error("验证码输入有误，请重新输入");
        refreshCaptcha(); // 刷新验证码
        form.captcha = ''; // 清空验证码输入
        return;
      }

      loading.value = true;
      try {
        if (isLogin.value) {
          // 登录逻辑保持不变
          const res = await login({
            username: form.username,
            password: form.password
          });

          if (res.code === 1 && res.data?.token) {
            ElMessage.success("登录成功");
            store.dispatch("login", {
              token: res.data.token,
              username: res.data.username
            });
            router.push("/home");
          } else {
            throw new Error(res.msg || "登录失败");
          }
        } else {
          // 注册逻辑
          const res = await register({
            username: form.username,
            password: form.password,
            gender: form.gender,
            job: form.job,
            phone: form.phone
          });

          if (res.code === 1) {
            ElMessage.success("注册成功，请登录");
            isLogin.value = true; // 切换到登录界面
            // 清空表单
            form.username = '';
            form.password = '';
            form.confirmPassword = '';
            form.captcha = '';
            form.phone = '';
          } else {
            throw new Error(res.msg || "注册失败");
          }
        }
      } catch (error: any) {
        ElMessage.error(error.message);
      } finally {
        loading.value = false;
      }
    }
  });
};

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  form.username = ''
  form.password = ''
  form.confirmPassword = ''
  form.captcha = ''
  form.phone = ''
  refreshCaptcha()
}

// 验证码相关
function generateCaptcha() {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars[Math.floor(Math.random() * chars.length)]
  }
  return result
}

const captchaHTML = computed(() => {
  return form.verifyCode.split('').map(char =>
      `<span style="color: ${getRandomColor()}; transform: ${getRandomRotation()}">${char}</span>`
  ).join('')
})

function getRandomColor() {
  return `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
}

function getRandomRotation() {
  return `rotate(${Math.random() * 30 - 15}deg)`
}

const refreshCaptcha = () => {
  form.verifyCode = generateCaptcha()
}

// 输入框焦点效果
const handleFocus = (event: Event) => {
  const target = event.target as HTMLElement
  const parent = target.closest('.el-form-item')
  if (parent) {
    parent.classList.add('focused')
  }
}

const handleBlur = (event: Event) => {
  const target = event.target as HTMLElement
  const parent = target.closest('.el-form-item')
  if (parent) {
    parent.classList.remove('focused')
  }
}
</script>

<style scoped>
.login-wrapper {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  position: relative;
  overflow: hidden;
}

.login-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
  pointer-events: none;
}

.particle-container {
  position: absolute;
  width: 100%;
  height: 100%;
}

.particle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.2) 100%);
  border-radius: 50%;
  animation: float 6s infinite ease-in-out;
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) translateX(0) scale(1);
    opacity: 0.7;
  }
  25% {
    transform: translateY(-30px) translateX(15px) scale(1.2);
    opacity: 1;
  }
  50% {
    transform: translateY(-60px) translateX(-10px) scale(0.8);
    opacity: 0.5;
  }
  75% {
    transform: translateY(-30px) translateX(-20px) scale(1.1);
    opacity: 0.8;
  }
}

/* 页面标题样式 */
.page-title {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2;
  text-align: center;
  animation: titleFadeIn 1.5s ease-out;
}

.title-text {
  font-size: 42px;
  font-weight: 700;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 50%, #ffffff 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 4px 20px rgba(255, 255, 255, 0.3);
  margin: 0;
  letter-spacing: 2px;
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
  position: relative;
}

.title-text::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.3));
  border-radius: 15px;
  z-index: -1;
  filter: blur(20px);
}

.title-decoration {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.decoration-line {
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.8), transparent);
  border-radius: 1px;
  animation: lineGlow 2s ease-in-out infinite alternate;
}

.decoration-circle {
  width: 12px;
  height: 12px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.4) 100%);
  border-radius: 50%;
  box-shadow: 0 0 15px rgba(255, 255, 255, 0.6);
  animation: circleRotate 3s linear infinite;
}

@keyframes titleFadeIn {
  0% {
    opacity: 0;
    transform: translateX(-50%) translateY(-30px);
  }
  100% {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

@keyframes lineGlow {
  0% {
    opacity: 0.5;
    transform: scaleX(0.8);
  }
  100% {
    opacity: 1;
    transform: scaleX(1.2);
  }
}

@keyframes circleRotate {
  0% {
    transform: rotate(0deg) scale(1);
    box-shadow: 0 0 15px rgba(255, 255, 255, 0.6);
  }
  50% {
    transform: rotate(180deg) scale(1.2);
    box-shadow: 0 0 25px rgba(255, 255, 255, 0.8);
  }
  100% {
    transform: rotate(360deg) scale(1);
    box-shadow: 0 0 15px rgba(255, 255, 255, 0.6);
  }
}

.login-container {
  position: relative;
  z-index: 1;
  margin-top: 80px;
  transition: margin-top 0.3s ease;
}

.login-container.no-title {
  margin-top: 0;
}

.login-card {
  width: 450px;
  padding: 0;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2), 0 8px 25px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
  transition: all 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.25), 0 12px 35px rgba(0, 0, 0, 0.15);
}

.digital-clock {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin: 30px 0;
  font-family: 'Courier New', monospace;
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea, #764ba2);
  padding: 20px;
  border-radius: 15px;
  box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.2);
}

.time-segment {
  background: rgba(255, 255, 255, 0.2);
  padding: 12px 16px;
  border-radius: 10px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.time-segment:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.time-number {
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.colon {
  color: #ffffff;
  animation: blink 1.5s infinite ease-in-out;
  font-size: 32px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

.login-form {
  padding: 30px;
  background: rgba(255, 255, 255, 0.1);
  margin: 0;
}

.captcha-container {
  margin-bottom: 25px;
}

.captcha-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-box {
  padding: 8px 15px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 8px;
  cursor: pointer;
  user-select: none;
  font-size: 18px;
  letter-spacing: 3px;
  border: 2px solid rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.captcha-box:hover {
  background: linear-gradient(135deg, #e9ecef, #dee2e6);
  border-color: rgba(102, 126, 234, 0.5);
  transform: scale(1.02);
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.toggle-btn-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.submit-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  position: relative;
  overflow: hidden;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a67d8, #6b46c1);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);
}

.submit-btn:active {
  transform: translateY(0);
}

.toggle-btn {
  width: auto;
  min-width: 200px;
  height: 45px;
  background: transparent;
  border: 2px solid rgba(102, 126, 234, 0.3);
  border-radius: 25px;
  color: #667eea;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  padding: 0 20px;
}

.toggle-btn:hover {
  background: rgba(102, 126, 234, 0.1);
  border-color: rgba(102, 126, 234, 0.5);
  color: #5a67d8;
  transform: translateY(-1px);
}

.el-form-item {
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

.el-form-item.focused {
  transform: translateX(3px);
}

/* 自定义输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 2px solid rgba(102, 126, 234, 0.2);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.el-input__inner) {
  font-size: 14px;
  padding: 12px 15px;
}

/* 单选按钮和选择器样式 */
:deep(.el-radio) {
  margin-right: 20px;
  font-weight: 500;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #667eea;
  border-color: #667eea;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

/* 响应式布局 */
@media (max-width: 576px) {
  .page-title {
    top: 30px;
  }

  .title-text {
    font-size: 28px;
    letter-spacing: 1px;
  }

  .decoration-line {
    width: 40px;
  }

  .login-container {
    margin-top: 60px;
  }

  .login-container.no-title {
    margin-top: 0;
  }

  .login-card {
    width: 90%;
    margin: 0 15px;
  }

  .button-group {
    flex-direction: column;
  }

  .submit-btn,
  .toggle-btn {
    margin: 5px 0;
  }
}

@media (max-width: 768px) {
  .title-text {
    font-size: 36px;
  }

  .login-container {
    margin-top: 70px;
  }

  .login-container.no-title {
    margin-top: 0;
  }
}
</style>